extends Node
class_name StorySystem

# 剧情状态
enum StoryState {
	INACTIVE,   # 未激活
	ACTIVE,     # 激活中
	COMPLETED,  # 已完成
	FAILED      # 失败
}

# 剧情类型
enum StoryType {
	MAIN_QUEST,    # 主线任务
	SIDE_QUEST,    # 支线任务
	RANDOM_EVENT,  # 随机事件
	HIDDEN_QUEST   # 隐藏任务
}

# 当前主线进度
var current_chapter: int = 0
var current_quest: int = 0

# 已完成的剧情
var completed_quests: Dictionary = {}

# 剧情数据库
var story_database: Dictionary = {}

# 随机事件池
var random_event_pool: Array = []

# 事件冷却时间
var event_cooldown: int = 0
var min_event_interval: int = 10  # 最小事件间隔（游戏内时间单位）

# 信号
signal quest_started(quest_id, quest_data)
signal quest_completed(quest_id, rewards)
signal quest_failed(quest_id)
signal random_event_triggered(event_id, event_data)
signal dialogue_started(dialogue_data)
signal chapter_changed(chapter_id)

# 初始化剧情系统
func _init() -> void:
	pass

# 当节点准备就绪
func _ready() -> void:
	
	#记载datamanager数据
	_load_story_database();
	
	# 初始化随机事件池
	_initialize_random_event_pool()

# 加载剧情数据库
func _load_story_database() -> void:
	# 从DataManager获取剧情数据
	print("_load_story_database")
	# 尝试从场景树中获取DataManager节点
	var data_manager = get_node_or_null("/root/data/DataManager")
	if data_manager == null:
		# 如果找不到，尝试从当前节点向上查找
		var current_scene = get_tree().get_current_scene()
		if current_scene:
			data_manager = current_scene.get_node_or_null("DataManager")
			print("尝试从当前场景获取DataManager: ", data_manager)
	if data_manager:
		story_database = data_manager.story_data
		print("成功获取到DataManager的story_data")
	else:
		print("警告：无法找到DataManager节点")
		
		# 如果数据为空，初始化一个默认的数据库
		if story_database.is_empty():
			_create_default_story_database()
		
		# 发出章节变化信号
		emit_signal("chapter_changed", current_chapter)

# 创建默认剧情数据库
func _create_default_story_database() -> void:
	# 初始化基本结构
	story_database = {
		"chapters": {},
		"side_quests": {},
		"random_events": {},
		"hidden_quests": {}
	}
	
	# 添加主线章节
	story_database["chapters"]["0"] = {
		"title": "踏入修仙之路",
		"description": "你刚刚踏入修仙世界，需要学习基本的修炼方法。",
		"quests": {
			"0": {
				"title": "拜师学艺",
				"description": "寻找一位师傅学习修炼基础。",
				"state": StoryState.ACTIVE,
				"objectives": ["找到青云门", "拜见掌门", "获得入门功法"],
				"rewards": {
					"experience": 100,
					"spirit_stones": 50,
					"items": ["基础功法卷轴"]
				},
				"dialogues": {
					"start": {
						"npc": "青云门掌门",
						"content": "年轻人，我看你骨骼清奇，是个修炼的好苗子。愿意入我青云门修行吗？",
						"choices": ["愿意", "我再考虑考虑"]
					},
					"complete": {
						"npc": "青云门掌门",
						"content": "很好，这是我们青云门的入门功法，好好修炼吧！",
						"choices": ["谢谢师傅"]
					}
				}
			},
			"1": {
				"title": "初学修炼",
				"description": "学习基础功法，提升修为。",
				"state": StoryState.INACTIVE,
				"requirements": {
					"quest_completed": ["0"]
				},
				"rewards": {
					"experience": 200,
					"spirit_stones": 100
				}
			}
		}
	}
	
	# 添加支线任务
	story_database["side_quests"]["s0"] = {
		"title": "寻找灵药",
		"description": "为师傅寻找一味名为'紫灵芝'的灵药。",
		"state": StoryState.INACTIVE,
		"requirements": {
			"min_level": 2
		},
		"rewards": {
			"experience": 150,
			"spirit_stones": 80,
			"items": ["初级丹方"]
		},
		"location": "灵药山谷"
	}
	
	# 添加随机事件
	story_database["random_events"]["r0"] = {
		"title": "灵兽出没",
		"description": "你在山林中遇到了一只受伤的灵兽，它似乎需要帮助。",
		"weight": 3,
		"requirements": {
			"min_level": 1
		},
		"choices": ["帮助灵兽", "无视离开", "捕获灵兽"],
		"outcome": {
			"0": {
				"description": "你帮助了灵兽疗伤，它感激地离开了，但留下了一枚灵石作为谢礼。",
				"rewards": {
					"spirit_stones": 30,
					"karma": 10
				}
			},
			"1": {
				"description": "你选择离开，灵兽悲伤地看着你远去。",
				"rewards": {}
			},
			"2": {
				"description": "你尝试捕获灵兽，但它拼命反抗，你们陷入了战斗。",
				"battle": "wounded_beast",
				"rewards": {
					"experience": 50,
					"karma": -5
				}
			}
		}
	}
	
	story_database["random_events"]["r1"] = {
		"title": "修仙者比试",
		"description": "你遇到了一位同门师兄，他提议进行一场友谊切磋。",
		"weight": 2,
		"requirements": {
			"min_level": 3,
			"quest_completed": ["0"]
		},
		"choices": ["接受挑战", "婉拒离开"],
		"outcome": {
			"0": {
				"description": "你接受了挑战，一场精彩的比试即将开始！",
				"battle": "fellow_disciple",
				"rewards": {
					"experience": 100
				}
			},
			"1": {
				"description": "你婉拒了挑战，师兄略显失望，但表示理解。",
				"rewards": {}
			}
		}
	}
	
	# 添加隐藏任务
	story_database["hidden_quests"]["h0"] = {
		"title": "古老的传承",
		"description": "你偶然发现了一个古老的洞穴，里面似乎隐藏着不为人知的秘密。",
		"state": StoryState.INACTIVE,
		"trigger": {
			"location": "神秘山洞",
			"item_required": "古老的钥匙"
		},
		"rewards": {
			"experience": 500,
			"spirit_stones": 300,
			"items": ["失传的功法"]
		}
	}

# 初始化随机事件池
func _initialize_random_event_pool() -> void:
	# 清空事件池
	random_event_pool.clear()
	
	# 检查story_database中是否有随机事件数据
	if not story_database.has("random_events") or story_database["random_events"].is_empty():
		return
	
	# 遍历所有随机事件
	for event_id in story_database["random_events"]:
		var event_data = story_database["random_events"][event_id]
		
		# 检查事件是否已完成
		if completed_quests.has(event_id):
			continue
		
		# 检查事件条件（如玩家等级要求等）
		if event_data.has("requirements") and not _check_event_requirements(event_data["requirements"]):
			continue
		
		# 根据事件权重添加到事件池中
		var weight = event_data.get("weight", 1)
		for i in range(weight):
			random_event_pool.append(event_id)
	
	# 打乱事件池顺序
	random_event_pool.shuffle()

# 检查事件要求
func _check_event_requirements(requirements: Dictionary) -> bool:
	# 获取玩家引用
	var player = get_node("/root/GameManager").player
	if not player:
		return false
	
	# 检查等级要求
	if requirements.has("min_level") and player.level < requirements["min_level"]:
		return false
	
	# 检查境界要求
	if requirements.has("min_realm") and player.cultivation_realm < requirements["min_realm"]:
		return false
	
	# 检查灵石要求
	if requirements.has("min_spirit_stones") and player.spirit_stones < requirements["min_spirit_stones"]:
		return false
	
	# 检查已完成任务要求
	if requirements.has("quest_completed"):
		for quest_id in requirements["quest_completed"]:
			if not completed_quests.has(quest_id):
				return false
	
	return true

# 获取随机事件
func get_random_event() -> Dictionary:
	# 检查随机事件池是否为空
	if random_event_pool.is_empty():
		# 重新初始化随机事件池
		_initialize_random_event_pool()
		
		# 如果仍然为空，返回空字典
		if random_event_pool.is_empty():
			return {}
	
	# 从事件池中随机选择一个事件ID
	var event_index = randi() % random_event_pool.size()
	var event_id = random_event_pool[event_index]
	
	# 从事件池中移除该事件，避免短时间内重复触发
	random_event_pool.remove_at(event_index)
	
	# 获取事件数据
	var event_data = story_database["random_events"].get(event_id, {})
	
	# 添加事件ID到事件数据中
	if not event_data.is_empty():
		event_data["id"] = event_id
	
	return event_data

# 获取主线任务
func get_main_quest() -> Dictionary:
	# 检查是否有主线章节数据
	if not story_database.has("chapters") or story_database["chapters"].is_empty():
		return {}
	
	# 获取当前章节
	var chapter_id = str(current_chapter)
	if not story_database["chapters"].has(chapter_id):
		return {}
	
	# 获取当前章节数据
	var chapter_data = story_database["chapters"][chapter_id]
	
	# 获取当前任务
	var quest_id = str(current_quest)
	if not chapter_data["quests"].has(quest_id):
		return {}
	
	# 获取任务数据
	var quest_data = chapter_data["quests"][quest_id]
	
	# 检查任务是否已完成
	var full_quest_id = chapter_id + "_" + quest_id
	if completed_quests.has(full_quest_id):
		# 尝试获取下一个任务
		var next_quest_id = str(current_quest + 1)
		if chapter_data["quests"].has(next_quest_id):
			current_quest += 1
			quest_data = chapter_data["quests"][next_quest_id]
			full_quest_id = chapter_id + "_" + next_quest_id
		else:
			# 尝试获取下一章节的第一个任务
			var next_chapter_id = str(current_chapter + 1)
			if story_database["chapters"].has(next_chapter_id):
				current_chapter += 1
				current_quest = 0
				emit_signal("chapter_changed", current_chapter)
				return get_main_quest()
			else:
				# 所有主线任务已完成
				return {}
	
	# 添加任务ID到任务数据中
	quest_data["id"] = full_quest_id
	
	return quest_data
